interface Config {
  request: Function
  delay?: number
  isRequestResolve?: boolean
}

const DEFAULT_DELAY = 2000

/**
 * ota渠道详情轮询
 * @param config 配置请求接口
 * @param config.request 请求接口
 * @param config.delay 轮询间隔时间，默认2000ms
 * @param config.isRequestResolve 请求接口status是否为0，如果为0，且有closeMsg，则直接返回closeMsg
 */
const otaLoop = (config: Config) => {
  const { request, delay = DEFAULT_DELAY } = config
  if (typeof request !== 'function') throw new Error(`getFuncOnLoopCondition: request must be a function, but got ${typeof request}`)

  let timer: any = null

  const result = {
    closeMsg: null,
    verifyFlag: null,
    extraDataJson: {},
    loop: null,
  }

  const loop = (isRequestResolve = false) => {
    return request()
      .then((response: any) => {
        const { status, closeMsg, extraDataJson, verifyFlag } = response

        // 如果请求接口status为0，且有closeMsg，则直接返回closeMsg
        if (!isRequestResolve && status === 0 && closeMsg) {
          clearTimeout(timer)
          timer = null
          return { ...result, closeMsg }
        } else if (verifyFlag === 1) {
          clearTimeout(timer)
          timer = null
          return { ...result, verifyFlag }
        } else if (Object.keys(extraDataJson).length > 0) {
          clearTimeout(timer)
          timer = null
          return { ...result, extraDataJson }
        } else {
          timer = setTimeout(loop, delay)
        }
      })
      .catch((error: any) => {
        clearTimeout(timer)
        timer = null
        console.error('otaLoop error:', error)
      })
  }

  const clear = () => {
    clearTimeout(timer)
    timer = null
  }

  return { loop, clear }
}

export default otaLoop
